<template>
	<view class="Achievememt">
		<header class="header Column">
			<!-- 一级导航 -->
			<view class="firstLevelNav Row">
				<text v-for="(item, index) in firstNav" :key="index" @click="firstSwitch(index,item.type)"
					:class=" firstIndex == index ? 'fristNavActive' : 'fristNav' ">{{ item.name }}</text>
			</view>

			<!-- 二级导航 -->
			<view class="secondaryNav Row justifyCont-bet">
				<view class="secondaryNav_childs Row">
					<view class="tabItem" :class="{'active' : index == current}" @click="clickTab(index,item.type)"
						v-for="(item,index) in tabItemList" :key="index">
						{{item.name}}
					</view>
				</view>

				<view class="secondaryNav_childs Row justifyCont-bet" @click="show = true">
					<view class="iconfont" style="font-size: 21px;">&#xe600;</view>
					<view class="">筛选</view>
				</view>
			</view>

			<view class="sumReward Row">
				<view class="sumReward_Text">总数量数</view>
				<view class="sumReward_num">{{totalBandwidth}}</view>
			</view>
		</header>

		<view class="Achievememt_detailList">
			<view v-if="detailList.length != 0">
				<view class="detailBox Column" v-for="(item,index) in detailList" :key="index">
					<view class="detail-title Row justifyCont-bet">
						<view class="Row">
							<h4>{{ item.user.username }}</h4>
							<view class="level Row">{{item.user.group.name}}</view>
						</view>
						<view
							:class=" item.onlineStatus == '1' ? 'onlineStatus fontSize16 paddingBot4' : 'onlineStatuss fontSize16 paddingBot4'">
							{{ item.onlineStatus == '1' ? '在线' : '离线' }}</view>
					</view>

					<view class="detail-items Column">
						<view class="productID Row">
							<h4 class="h4">设备编号</h4>{{ item.deviceSn }}
						</view>
						<view class="productID Row">
							<h4 class="h4">流量数</h4>{{item.totalBandwidth}}
						</view>
					</view>
				</view>
			</view>

			<view class="null" v-else>
				暂无数据
			</view>
		</view>

		<u-popup :show="show" mode="top" @close="close" @open="open">
			<scroll-view scroll-y="true" class="popupBox_Body"
				:style=" current == 1 ? 'height: 56vh;' : 'height: 30vh;'">
				<view class="item Column" v-if="current == 1">
					<view class="itemTitle">月份</view>
					<view class="monthList Row">
						<view :class="monthList_Index == index ? 'active Row' : 'monthChild Row'"
							v-for="(item,index) in monthList" :key="index" @click="monthCut(item.type,index)">
							{{item.name}}
						</view>
					</view>
				</view>
				<!-- <view class="item Row" style="margin-bottom: 20rpx;">
					<view style="width: 40%;" class="itemTitle">姓名</view>
					<input type="text" :placeholder="this.submitInfo.realname" class="inputCSS"
						data-submitInfo="realname" @input="inputVal" />
				</view> -->
				<view class="item Row" style="margin: 6px 0;">
					<view style="width: 40%;" class="itemTitle">手机号</view>
					<input type="text" :placeholder="this.submitInfo.mobile" class="inputCSS" data-submitInfo="mobile"
						@input="inputVal" />
				</view>
				<view class="item Column">
					<view class="itemTitle">等级</view>
					<view class="monthList Row">
						<view v-if="item.name" :class="levels_Index == index ? 'active Row' : 'monthChild Row'"
							v-for="(item,index) in levels" :key="index" @click="levelCut(item.id,index)">
							{{item.name}}
						</view>
					</view>
				</view>
			</scroll-view>

			<footer class="footBox Row">
				<view class="reset Row" @click="reset">重置</view>
				<view class="finish Row" @click="finish">完成</view>
			</footer>
		</u-popup>
	</view>
</template>

<script>
	import {
		apiPersonalBandwidth,
		apiTeamBandwidth
	} from '@/api/team.js';
	import {
		apiTeamLog,
		apiGroupList
	} from '@/api/reward.js';
	import formatTimestamp from '@/utils/util.js';

	export default {
		data() {
			return {
				newTimestamp: Math.floor(Date.now() / 1000),
				show: false,

				firstNav: [{
					name: "个人",
					type: 'personal'
				}, {
					name: "团队",
					type: 'team'
				}],
				firstIndex: 0, // 打卡天数 = 0, 总里程 = 1
				firstType: 'personal',

				tabItemList: [{
						'name': '昨日',
						'type': 'd' //t
					},
					{
						'name': '月',
						'type': 'm'
					},
					{
						'name': '累计',
						'type': 't'
					}
				],
				current: 0,
				currentType: 'd',

				monthList: [{
					name: '一月',
					type: '01' //t
				}, {
					name: '二月',
					type: '02' //t
				}, {
					name: '三月',
					type: '03' //t
				}, {
					name: '四月',
					type: '04' //t
				}, {
					name: '五月',
					type: '05' //t
				}, {
					name: '六月',
					type: '06' //t
				}, {
					name: '七月',
					type: '07' //t
				}, {
					name: '八月',
					type: '08' //t
				}, {
					name: '九月',
					type: '09' //t
				}, {
					name: '十月',
					type: '10' //t
				}, {
					name: '十一月',
					type: '11' //t
				}, {
					name: '十二月',
					type: '12' //t
				}],
				monthList_Index: "", // 下标
				monthList_type: "",
				monthList_date: "",
				range: {
					firstDays: '',
					lastDays: ''
				},

				levels: [],
				levels_Index: "", // 下标
				level_id: "", // id

				submitInfo: {
					realname: '',
					mobile: '',
				},

				detailList: [],
				totalBandwidth: 0,

				current_page: 1,
				last_page: 1
			}
		},
		onLoad(options) {
			this.getLevel(); // 会员等级
			this.getData(); // 获取当前年月日
		},
		onShow() {
			// 获取数据列表
			this.dataReset();
			this.homePageData();
		},
		methods: {
			// 一级级导航切换
			firstSwitch(index, type) {
				this.firstIndex = index;
				this.firstType = type;
				// 刷新数据
				// this.clickTab(0, "d");
				this.reset();
			},
			// 二级导航切换
			clickTab(index, type) {
				this.current = index;
				this.currentType = type;
				// 刷新数据
				this.dataReset();
				this.homePageData()
			},

			dataReset() {
				this.current_page = 1;
				this.last_page = 1;
				this.detailList = [];
			},
			reset() { // 重置
				let that = this;
				that.dataReset(); // 列表数据重置
				that.resetMonth(); // 重置月份下标
				that.submitInfo.realname = "";
				that.submitInfo.mobile = "";
				that.levels_Index = 0;
				that.level_id = "";

				that.homePageData();
				that.show = false;
			},
			// 重置月份
			resetMonth() {
				var now = new Date();
				// 获取月
				var month = now.getMonth() + 1; // 月份从0开始，所以+1
				month = month < 10 ? '0' + month : month;
				const index = this.monthList.findIndex(item => item.type == month);
				this.monthList_Index = index;
				this.monthList_type = "";
			},

			// 筛选按钮
			finish() {
				let that = this;
				that.dataReset();
				that.homePageData();

				that.show = false;
			},
			// 手机号筛选
			inputVal(e) {
				let name = e.currentTarget.dataset.submitinfo;
				let Val = e.detail.value.trim();
				this.submitInfo[name] = Val;
			},
			// 月份筛选
			monthCut(e, index) {
				this.monthList_Index = index;
				this.monthList_type = this.monthList[index].type;
				this.getMonthRange(this.monthList_type);
			},
			// 等级筛选
			levelCut(e, index) {
				this.levels_Index = index;
				this.level_id = e;
			},

			getLevel() { // 获取等级列表
				let that = this;
				apiGroupList({}).then(res => {
					if (res.code == 0) {
						uni.$u.toast(res.msg);
						return false;
					}
					let newInfo = {
						id: "",
						name: "全部"
					};
					let data = res.data;
					data.unshift(newInfo);
					that.levels = data;
				}).catch(err => {
					console.log(err)
				})
			},

			homePageData() {
				let that = this;

				const {
					firstDay,
					lastDay
				} = that.getFirstAndLastDay(that.monthList_date);
				const params = {
					mobile: that.submitInfo.mobile,
					group_id: that.level_id,
					page: that.current_page,
				};
				// 处理 date_start 和 date_end（支持 current == 3 的情况）  累计数据 不传月份 
				if (that.current === 2) {
					params.date_start = '';
					params.date_end = '';
				} else if (that.current) {
					if (that.monthList_type) {
						params.date_start = that.range.firstDays;
						params.date_end = that.range.lastDays;
					} else {
						params.date_start = firstDay;
						params.date_end = lastDay;
					}
				} else {
					params.date_start = that.monthList_date;
					params.date_end = that.monthList_date;
				}


				let apiFunc = null;
				if (that.firstType == 'personal') {
					apiFunc = apiPersonalBandwidth;
				} else if (that.firstType == 'team') {
					apiFunc = apiTeamBandwidth;
				}

				apiFunc({
					params
				}).then(res => {
					if (res.code == 0) {
						uni.$u.toast(res.msg);
						return;
					}
					let array = res.data.list.data;
					array.forEach(item => {
						item.registrationTime = formatTimestamp(item.jointime, 'YYYY-MM-DD HH:mm:ss');
						that.detailList.push(item)
					})
					that.totalBandwidth = res.data.totalBandwidth;
					that.last_page = res.data.list.last_page;
				}).catch(err => {
					console.log(err)
				})
			},

			// 获取当前年月日
			getData() {
				var now = new Date();

				// 获取年、月、日
				var year = now.getFullYear();
				var month = now.getMonth() + 1; // 月份从0开始，所以+1
				var day = now.getDate() - 1;

				// 补零处理
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;

				// 设置 picker 的索引
				this.monthList_Index = Number(month) - 1;
				// 拼接日期格式 YYYY-MM-DD
				this.monthList_date = year + '-' + month + '-' + day;
			},
			// 默认切换月份 获取当前年月日开始 结束时间  日1号——31号   (截取字符串不可用!!! 每月天数不同)
			getFirstAndLastDay(dateStr) {
				const date = new Date(dateStr);
				if (isNaN(date.getTime())) {
					console.error('无效的日期格式');
					return null;
				}

				const year = date.getFullYear();
				const month = date.getMonth() + 1; // 月份从 0 开始

				// 获取当月第一天
				const firstDay = new Date(year, month - 1, 1);
				// 获取下个月的第一天，再往前一天就是当前月的最后一天
				const nextMonth = new Date(year, month, 1);
				const lastDay = new Date(nextMonth - 1);

				function formatDate(date) {
					const y = date.getFullYear();
					const m = String(date.getMonth() + 1).padStart(2, '0');
					const d = String(date.getDate()).padStart(2, '0');
					return `${y}-${m}-${d}`;
				}

				return {
					firstDay: formatDate(firstDay),
					lastDay: formatDate(lastDay)
				};
			},
			// 筛选月份 获取当前年月日开始 结束时间  日1号——31号   (截取字符串不可用!!! 每月天数不同)
			getMonthRange(monthStr) {
				const year = new Date().getFullYear();
				if (!/^\d{2}$/.test(monthStr) || parseInt(monthStr) < 1 || parseInt(monthStr) > 12) {
					uni.showToast({
						title: '请输入正确的月份',
						icon: 'none'
					});
					return;
				}

				const firstDay = new Date(year, parseInt(monthStr) - 1, 1);
				const lastDay = new Date(year, parseInt(monthStr), 0);

				function formatDate(date) {
					const y = date.getFullYear();
					const m = String(date.getMonth() + 1).padStart(2, '0');
					const d = String(date.getDate()).padStart(2, '0');
					return `${y}-${m}-${d}`;
				}

				this.range = {
					firstDays: formatDate(firstDay),
					lastDays: formatDate(lastDay)
				};
			},

			open() {
				this.show = true;
			},
			close() {
				this.show = false;
			},
		},
		onReachBottom() {
			let that = this;
			that.current_page++;
			if (that.current_page > that.last_page) {
				uni.$u.toast('暂无更多~');
				return false;
			}
			that.homePageData();
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F6F8;
	}

	.Achievememt {
		width: 100%;

		.header {
			width: 100%;
			position: fixed;
			top: 0;

			.sumReward {
				box-sizing: border-box;
				background-color: #F5F6F8;
				padding: 4px 12px 4px;

				&_Text {
					color: #1a1a1a;
					font-weight: 550;
				}

				&_num {
					padding: 0 0 0 6px;
				}
			}

			// er级导航
			.secondaryNav {
				width: 100%;
				box-sizing: border-box;
				background-color: #F5F6F8;
				padding: 12px;

				&_childs:first-child {
					width: 80%;
				}

				&_childs:last-child {
					width: 60px;
					font-size: 16px;
				}

				&_childs {
					font-size: 15px;

					.tabItem {
						color: #7E7E9A;
						text-align: center;
						border-radius: 8rpx;
						border: 1px solid #7E7E9A;
						padding: 3px 12px;
						margin-right: 12px;
					}

					.active {
						color: #fff;
						background-color: #0056FF;
						border: none;
						border-radius: 8rpx;
						padding: 3px 12px;
						margin-right: 12px;
					}
				}
			}

			// 一级导航
			.firstLevelNav {
				background-color: #fff;
				box-shadow: 4px 4px 10px #e6e6e6;

				.fristNavActive {
					position: relative;
				}

				.fristNavActive::after {
					content: '';
					width: 20px;
					height: 3px;
					border-radius: 12px;
					background-color: #0056FF;
					position: absolute;
					left: 166rpx;
					bottom: 8rpx;
				}

				.fristNavActive,
				.fristNav {
					width: 50%;
					color: #7E7E9A;
					font-size: 16px;
					text-align: center;
					padding: 12px 0;
				}

				.fristNavActive {
					color: #0056FF !important;
				}
			}
		}

		&_detailList {
			padding: 12px;
			margin-top: 120px;

			.null {
				height: 70vh;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.detailBox {
				align-items: center;
				justify-content: space-between;
				background-color: #fff;
				border-radius: 6px;
				border-bottom: 2rpx solid #F5F6F8;
				padding: 12px;
				margin-bottom: 12px;

				.onlineStatus {
					color: #23c96d;
				}

				.onlineStatuss {
					color: #a7a7a7;
				}


				.detail-items {
					width: 100%;
					margin-top: 12px;

					.h4 {
						color: #7E7E9A;
						font-weight: 500;
						margin-right: 6px;
					}

					.productID {
						font-size: 30rpx;
					}
				}

				.detail-title {
					justify-content: space-between;
					width: 100%;
					font-size: 18px;
					border-bottom: 1px solid #f6f5fa;
					padding-bottom: 12px;

					.enterprise_type {
						color: #0056FF;
						border-radius: 4px;
						border: 1px solid #c1cfff;
						padding: 2px 6px;
						margin-right: 6px;
					}

					.level {
						justify-content: center;
						color: #fff;
						font-size: 14px;
						background-color: #2b72fb;
						border-radius: 4rpx;
						padding: 4rpx 12rpx;
						margin-left: 12rpx;
					}
				}

				&_right {
					width: 100%;
					color: #7E7E9A;
					justify-content: space-around;
					align-items: center;
					margin-top: 20rpx;

					.money {
						width: 35%;
						text-align: center;
						font-size: 32rpx;
						display: flex;
						justify-content: center;
					}

					.time {
						width: 35%;
						font-size: 32rpx;
						display: flex;
						justify-content: center;
					}
				}

				&_left {
					width: 100%;
					justify-content: space-between;
					align-items: flex-start;

					.name {
						font-weight: 550;
					}

					.productID {
						display: flex;
						flex-direction: row;
						align-items: center;
						width: 62%;
						font-size: 16px;
					}
				}
			}
		}

		.popupBox_Body {
			width: 90.5%;
			height: 54vh;
			padding: 0 20px;

			.monthList {
				flex-wrap: wrap;
				width: 100%;

				// .monthChild:nth-last-child(1),
				// .monthChild:nth-last-child(2){
				// 	margin-bottom: 0;
				// }

				.active {
					justify-content: center;
					width: 22%;
					color: #0056ff;
					background-color: #e6efff;
					padding: 20rpx 0;
					margin-bottom: 30rpx;
					margin-right: 10px;
				}

				.monthChild:nth-child(4n) {
					margin-right: 0;
				}

				.monthChild {
					justify-content: center;
					width: 22%;
					color: #1a1a1a;
					background-color: #f6f6f6;
					padding: 20rpx 0;
					margin-bottom: 30rpx;
					margin-right: 10px;
				}
			}

			.inputCSS {
				width: 50%;
				background-color: #f6f6f6;
				padding: 20rpx;
			}

			.itemTitle {
				font-size: 32rpx;
				padding: 20rpx 0;
			}
		}

		.footBox {
			width: 100%;
			border-top: 1px solid #F5F6F8;

			.reset,
			.finish {
				justify-content: center;
				width: 50%;
				font-size: 34rpx;
				padding: 20rpx 0;
			}

			.finish {
				color: #fff;
				background-color: #0056FF;
			}
		}
	}
</style>